package com.zhouw.printtextview;

import android.animation.ValueAnimator;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.widget.TextView;

/**
 * 银川鸿联科技有限公司
 * 作者 周伟 on 2018-06-08.
 * 邮箱 1300012858@qq.com
 */

public class PrintTextView extends TextView {
    private long duration = 1000;
    private boolean print = false;
    public PrintTextView(Context context) {
        this(context, null);
    }

    public PrintTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        TypedArray td = context.obtainStyledAttributes(attrs, R.styleable.PringTextView);
        print = td.getBoolean(R.styleable.PringTextView_print, false);
        duration = td.getInt(R.styleable.PringTextView_duration, 1000);
        int fontStyle = td.getInteger(R.styleable.PringTextView_fontStyle, 0);
        switch(fontStyle){
            case 1:
                setFontStyle(context, "DianedeFrance");
                break;
            case 2:
                setFontStyle(context, "HWXK");
                break;
            case 3:
                setFontStyle(context, "PalaceScriptMt");
                break;
            case 0:
                break;
        }
         if(print == false){
             return;
         }
        CharSequence txt = getText();
        final char[] target = txt.toString().toCharArray();
        ValueAnimator animator = ValueAnimator.ofInt(target.length)
        .setDuration(duration);
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                int length = (int)animation.getAnimatedValue();
                setText(target, 0, length);
            }
        });
        animator.start();
    }

    private void setFontStyle(Context context, String ttfName){
        Typeface typeface = FontFamily.getTypeFace(context, ttfName);
        setTypeface(typeface);
    }
}
